/*商品类别*/
$(document).ready(function(){
	var currentPage = 1;
	var pageSize = 10;
	var token = $.zui.store.get("token");
	var userId = $.zui.store.get("userId");
	var merInfId = $.zui.store.get("merInfId");
	
	var queryListFun = function(){
		//获取列表数据
		var queryListUrl = adminQueryUrl + categoryService + queryCategory;
		
		var param = "";
		//搜索参数
		if ($("#queryGoodsCategoryLike").val()!=''){
			param += "&GoodsCategoryLike="+$("#queryGoodsCategoryLike").val();
		}
		if (currentPage>0){
			param += "&currentPage="+(currentPage-1);
		}
		param += "&pageSize="+pageSize;
		param += "&currentPage="+(currentPage-1);
		
		console.log('queryListUrl='+queryListUrl);
		console.log('token='+token+",merchantId="+userId);
		console.log('param='+param);
		$.ajax({
			url:queryListUrl,
			type:'post',
			beforeSend:function(xhr){
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
				xhr.setRequestHeader("merchantId",userId);//辨别为商户用户
			},
			header:{"token":token,"userId":userId,"merchantId":userId},
			data:param,
			dataType:"JSON",
			success:function(result){
				console.log(result.success);
				console.log(result.pageList);
				if (result.success== '1'){
					
					$('#listDataGrid').empty();
					$('#listDataGrid').data('zui.datagrid',null);
					$('#listPager').empty();
					$('#listPager').data('zui.pager',null);
					
					$('#listDataGrid').datagrid({
						checkable: true,
					    checkByClickRow: true,
					    selectable: true,
					    dataSource: {
					        cols:[
					            {name: 'categoryName', label: '商品类别名称', width: 132},
					            {name: 'categoryParentId', label: '上级类别编号', width: 159},
					            {name: 'categorySortCode', label: '排序码', width: 109},
					            {name: 'oprName', label: '操作员', width: 132},
					            {name: 'oprDate', label: '操作时间', width: 132},
					            {name: 'Category_ID', label: '商品类别编号', hidden:true}
					        ],
					        cache:false,
					        array:result.pageList
					    }
					 
					});	
					
					// 手动进行初始化
					$('#listPager').pager({
					    page: currentPage,
					    recPerPage:pageSize,
					    elements:['first_icon', 'prev_icon', 'pages', 'next_icon', 'last_icon', 'total_text','size_menu','goto'],
					    pageSizeOptions:[5,10,20,30,50,100],
					    recTotal: result.pageTotal
					});
				}
				else {
					new $.zui.Messager(result.msg, {
					    type: 'warning', // 定义颜色主题
					    placement: 'center' // 定义显示位置
					}).show();
				}
			},
			error:function(result){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning', // 定义颜色主题
				    placement: 'center' // 定义显示位置
				}).show();
			}
		});
	};
	//调起查询数据
	queryListFun();
	//查询
	$("#searchBtn").click(function(){
		queryListFun();
	});
	//监听分页，修改当前页，条数
	$('#listPager').on('onPageChange', function(e, state, oldState) {
		currentPage = state.page;
		pageSize = state.recPerPage;
		queryListFun();
	});
	
	//初始化添加
	$("#addBtn").click(function(){
		$("#addForm")[0].reset();
		var url = adminQueryUrl + categoryService + initAddCategoryMethod;
		var param = '';//请求到列表页面
		$.ajax({
			url:url,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){//设置请求头信息
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
				
			},
			headers:{'token':token,'userId':userId},
			data:param,
			success:function(data){
				console.log('data.categoryList='+data.categoryList);
				if (data.success=='1'){
					$('#addModal').modal('show', 'fit');
					$.fn.zTree.init($("#cateTree"), setting, data.categoryList);
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
		});
	});
	//添加保存
	$("#addSave").click(function(){
		var validLoginNameUrl = adminQueryUrl + categoryService + validCategoryName;
		$("#addForm").validate({
			rules:{
				catName:{
					"required":true
				},
				addCategoryName:{
					"required":true,
					"remote":{
						url:validLoginNameUrl,
						type:'get',
						beforeSend:function(xhr){//设置请求头信息
							xhr.setRequestHeader("token",token);
							xhr.setRequestHeader("userId",userId);
							xhr.setRequestHeader("merInfId",merInfId);
						},
						headers:{'token':token,'userId':userId,'merInfId':merInfId},
						dataType:'json',
						data:{
							'addCategoryName':function(){
								return $("#addCategoryName").val();
							},
							'catId':function(){
								return $("#catId").val();
							},
						}
					}
				},
				addSortNo:{
					"required":true
				},
			},
			messages:{
				addCategoryName:{
					"remote":"同级下商品类别已经存在"
				}
			},
			errorPlacement:function(error,element){
				error.appendTo(element.parent().parent());
			},
			submitHandler:function(form){
				$.ajax({
					url:adminQueryUrl + categoryService + addMethod,
					type:'post',
					dataType:'JSON',
					beforeSend:function(xhr){//设置请求头信息
						xhr.setRequestHeader("token:'"+token+"'");
						xhr.setRequestHeader("userId:'"+userId+"'");
						xhr.setRequestHeader("merInfId",merInfId);
					},
					headers:{'token':token,'userId':userId,'merInfId':merInfId},
					data:$(form).serialize(),
					success:function(data){
						console.log('data='+data);
						if (data.success == '1') {
		                	new $.zui.Messager('添加成功!', {
		    				    type: 'success',
		    				    placement:'center'
		    				}).show();
		                	$('#addModal').modal('hide', 'fit');
		                	queryListFun();
		                }
		                else{
		                	new $.zui.Messager(data.msg, {
		    				    type: 'warning',
		    				    placement:'center'
		    				}).show();
		                }
					},
					error:function(e){
						new $.zui.Messager('系统繁忙,请稍候再试!', {
	    				    type: 'warning',
	    				    placement:'center'
	    				}).show();
					}
				});
			}
		});
	});
	
	//初始化修改
	$("#updateBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要修改的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要修改的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$("#updateForm")[0].reset();
			$("#updateCategoryId").val(selectedItems[0].Category_ID);
			var url = adminQueryUrl + categoryService+initUpdateMethod;
			var param = 'updateCategoryId='+selectedItems[0].Category_ID;//请求到列表页面
			console.log('param='+param);
			$.ajax({
				url:url,
				type:'post',
				dataType:'JSON',
				beforeSend:function(xhr){//设置请求头信息
					xhr.setRequestHeader("token:'"+token+"'");
					xhr.setRequestHeader("userId:'"+userId+"'");
				},
				headers:{'token':token,'userId':userId},
				data:param,
				success:function(data){
					console.log('data='+data);
					if (data.success=='1'){
						$('#updateModal').modal('show', 'fit');
						$("#updateCategoryName").val(data.categoryMap.categoryName);
						$("#updatecatName").empty();
						$("#updateCategorySortNo").val(data.categoryMap.categorySortCode);
						$("#updateCategoryDescript").val(data.categoryMap.remark);
						$.fn.zTree.init($("#cateTree1"), setting1, data.categoryList);
					}
				},
				error:function(e){
					new $.zui.Messager('系统繁忙,请稍候再试!', {
					    type: 'warning',
					    placement:'center'
					}).show();
				}
			});
		}
	});
	//修改保存
	$("#updateSave").click(function(){
		var validLoginNameUrl = adminQueryUrl + categoryService + validCategoryName;
		$("#updateForm").validate({
			rules:{
				updatecatName:{
					"required":true
				},
				updateCategoryName:{
					"required":true,
				},	
				updateCategorySortNo:{
					"required":true
				},
			},
			errorPlacement:function(error,element){
				error.appendTo(element.parent().parent());
			},
			submitHandler:function(form){
					$.ajax({
					url:adminQueryUrl + categoryService+updateMethod,
					type:'post',
					dataType:'JSON',
					beforeSend:function(xhr){//设置请求头信息
						xhr.setRequestHeader("token",token);
						xhr.setRequestHeader("userId",userId);
					},
					headers:{'token':token,'userId':userId},
					data:$(form).serialize(),
					success:function(data){
						console.log('data='+data);
						if (data.success == '1') {
		                	new $.zui.Messager('修改成功!', {
		                		type: 'success',
		    				    placement:'center'
		    				}).show();
		                	$('#updateModal').modal('hide', 'fit');
		                	queryListFun();
		                }
		                else{
		                	new $.zui.Messager(data.msg, {
		    				    type: 'warning',
		    				    placement:'center'
		    				}).show();
		                }
					},
					error:function(e){
						new $.zui.Messager('系统繁忙,请稍候再试!', {
	    				    type: 'warning',
	    				    placement:'center'
	    				}).show();
					}
				});
			}
		});
	});
	
	//显示删除确认框
	$("#deleteBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要删除的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要删除的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$('#deleteModal').modal('show', 'fit');
		}
	});
	//删除菜单
	$("#deleteCategoryBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		var url = adminQueryUrl + categoryService + deleteCategoryMethod;
		var param = 'categoryId='+selectedItems[0].Category_ID;//请求到列表页面
		console.log('url='+url);
		console.log('param2='+param);
		$.ajax({
			url:url,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){//设置请求头信息
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
			},
			header:{'token':token,'userId':userId},
			data:param,
			success:function(data){
				console.log('data='+data);
				$('#deleteModal').modal('hide', 'fit');
				if (data.success=='1'){
	                	new $.zui.Messager('删除成功!', {
	    				    type: 'success',
	    				    placement:'center'
	    				}).show();
	                	queryListFun();
				}
                else{
                	new $.zui.Messager(data.msg, {
    				    type: 'warning',
    				    placement:'center'
    				}).show();
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
		});
	});
	//初始化详情
	$("#detailBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要查看的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要查看的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$("#detailForm")[0].reset();
			var url = adminQueryUrl + categoryService + detailCategoryMethod;
			var param = 'categoryId='+selectedItems[0].Category_ID;//请求到列表页面
			console.log('param='+param);
			$.ajax({
				url:url,
				type:'post',
				dataType:'JSON',
				beforeSend:function(xhr){//设置请求头信息
					xhr.setRequestHeader("token",token);
					xhr.setRequestHeader("userId",userId);
				},
				header:{'token':token,'userId':userId},
				data:param,
				success:function(data){
					console.log('data='+data);
					if (data.success=='1'){
						$('#detailModal').modal('show', 'fit');
						
						$("#detailCategoryName").html(data.categoryMap.categoryName);
						$("#detailCategoryCode").html(data.categoryMap.Category_ID);
						$("#detailParentName").html(data.categoryMap.mcategoryName);
						$("#detailSortNo").html(data.categoryMap.categorySortCode);
						$("#detailOprDate").html(data.categoryMap.oprDate);
						$("#detailDescription").html(data.categoryMap.remark);
						$("#detailOprId").html(data.categoryMap.oprId);
					}
				},
				error:function(e){
					new $.zui.Messager('系统繁忙,请稍候再试!', {
					    type: 'warning',
					    placement:'center'
					}).show();
				}
			});
		}
	});
	
});
//增加
function zTreeBeforeClick(treeId, treeNode, clickFlag) {
			var check = (treeNode && !treeNode.isParent);
			if (!check){
				//alert("只能选择子节点...");
				var catObj = $("#catName");
				catObj.attr("value", "");
			}
			return check;
		}
 
		function zTreeOnClick(event, treeId, treeNode) {
			var zTree = $.fn.zTree.getZTreeObj("cateTree"), nodes = zTree
					.getSelectedNodes(), v = "", ids = "";
			nodes.sort(function compare(a, b) {
				return a.id - b.id;
			});
			v =  nodes[0].categoryName;
			ids = nodes[0].Category_ID;
			//if (v.length > 0)
			//	v = v.substring(0, v.length - 1);
			var catObj = $("#catName"),catId = $("#catId");
			catObj.attr("value", v);
			catId.attr("value", ids);
		}
 
		function showMenu() {
			var cityObj = $("#catName");
			var cityOffset = $("#catName").offset();
			$("#menuContent").css({
				left : cityOffset.left + "px",
				top : cityOffset.top + cityObj.outerHeight() + "px"
			}).slideDown("fast");
 
			$("body").bind("mousedown", onBodyDown);
		}
		function hideMenu() {
			$("#menuContent").fadeOut("fast");
			$("body").unbind("mousedown", onBodyDown);
		}
		function onBodyDown(event) {
			if (!(event.target.id == "menuBtn"
					|| event.target.id == "menuContent" || $(event.target)
					.parents("#menuContent").length > 0)) {
				hideMenu();
			}
		}
		var setting = {
				view: {
					selectedMulti: false
				},
				data : {
					key : {
						name : "categoryName"
					},
					simpleData : {
						enable : true,
						idKey : "Category_ID",
						pIdKey : "categoryParentId",
						rootPId : 0
					}
				},
				callback: {
					//beforeClick: zTreeBeforeClick,
	                onClick: zTreeOnClick
	            }
			};
//修改
		function zTreeBeforeClick1(treeId, treeNode, clickFlag) {
			//var check = (treeNode && !treeNode.isParent);
			//if (!check){
			$("#updatecatName").empty();
			//}
			//return check;
		}
 
		function zTreeOnClick1(event, treeId, treeNode) {
			var zTree = $.fn.zTree.getZTreeObj("cateTree1"), nodes = zTree
					.getSelectedNodes(), v = "", ids = "";
			nodes.sort(function compare(a, b) {
				return a.id - b.id;
			});
			v=  nodes[0].categoryName;
			ids= nodes[0].Category_ID;
			//if (v.length > 0)
			//	v = v.substring(0, v.length - 1);
			var catObj = $("#updatecatName"),catId = $("#updatecatId");
			catObj.attr("value", v);
			catId.attr("value", ids);
		}
 
		function showMenu1() {
			var cityObj = $("#updatecatName");
			var cityOffset = $("#updatecatName").offset();
			$("#updatemenuContent").css({
				left : cityOffset.left + "px",
				top : cityOffset.top + cityObj.outerHeight() + "px"
			}).slideDown("fast");
 
			$("body").bind("mousedown", onBodyDown1);
		}
		function hideMenu1() {
			$("#updatemenuContent").fadeOut("fast");
			$("body").unbind("mousedown", onBodyDown1);
		}
		function onBodyDown1(event) {
			if (!(event.target.id == "menuBtn"
					|| event.target.id == "updatemenuContent" || $(event.target)
					.parents("#updatemenuContent").length > 0)) {
				hideMenu1();
			}
		}
		var setting1 = {
				view: {
					selectedMulti: false
				},
				data : {
					key : {
						name : "categoryName"
					},
					simpleData : {
						enable : true,
						idKey : "Category_ID",
						pIdKey : "categoryParentId",
						rootPId : 0
					}
				},
				callback: {
					//beforeClick: zTreeBeforeClick1,
	                onClick: zTreeOnClick1
	            }
			};